package com.wyh.shiro2_ssm.controller;

import com.wyh.shiro2_ssm.config.ShiroConfig;
import com.wyh.shiro2_ssm.service.SysUserService;
import com.wyh.shiro2_ssm.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@Controller
public class UserController {
    Logger log = LoggerFactory.getLogger(UserController.class);
//    显示登录页
    @GetMapping("login")
    public String showLoginView(){
        return "login";
    }
//    处理用户登录
    @PostMapping("dealLogin")
    public String dealLogin(UserVo userVo){
//        System.out.println(userVo.getLoginName()+userVo.getPassword());
        try {
//        认证过程
//        创建令牌
            UsernamePasswordToken token = new UsernamePasswordToken(userVo.getLoginName(),userVo.getPassword());
//        获取shiro主题对象
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            if (subject.isAuthenticated()){
                return "main";
            }
        } catch (AuthenticationException e) {
            log.error("认证失败");
        }
        return "login";
    }
//    显示主视图
    @GetMapping("main")
    public String showMainView(){
        return "main";
    }
//    显示1视图
    @RequiresPermissions(value = {"user_edit"})
    @GetMapping("one")
    public String showOneView(){
        return "one";
    }

//    显示2视图
    @RequiresPermissions(value = {"user_forbidden"})
    @GetMapping("two")
    public String showTwoView(){
        return "two";
    }

//    显示无权访问视图
    @GetMapping("unauth")
    public String showUnauthView(){
        return "unauth";
    }
    @GetMapping("logOut")
    public String logOut(){
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
//            清除业务会话信息
        } catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:login";
    }
}
